package com.qf.file.controller;

import com.qf.pickname.entity.Student;
import com.qf.pickname.service.StudentService;
import com.qf.pickname.vo.ResultVo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private StudentService studentService;

    // 获取配置文件中，key为 file.pic 的 value
    @Value("${file.pic}")
    private String fileDir;

//    public static final String FILE_DIR = "D:\\qd2305\\pic\\";
//    public static final String FILE_DIR = "/root/pic/";

    @RequestMapping("/picup")
    public ResultVo uploadpic(String name, MultipartFile avatar) throws IOException {

        if (name == null || "".equals(name)) {
            return new ResultVo(-1, "学生的名字为空了");
        }

        // 判断给定名字的学生对象是否存在
        Student student = studentService.getStudentByname(name);
        if (student != null) {
            //1. 存放上传的头像文件
            String picname = UUID.randomUUID().toString();
            String filepath = fileDir + picname;
            avatar.transferTo(new File(filepath));
            //2. 修改学生的avatar属性
            student.setAvatar(picname);
            return new ResultVo(1, "OK");
        } else {
            return new ResultVo(-1, "学生的名字不存在");
        }

    }

    @RequestMapping("/pic")
    public void pic(String picname, HttpServletResponse response) throws IOException {
        //1. 找到图片文件在服务器上的的存放目录，加上文件名得到文件的完整服务器路径
        String filepath = fileDir + picname;
        //2. 把图片的内容获取到然后放入 response 中
        IOUtils.copy(new FileInputStream(filepath), response.getOutputStream());
    }

}
